﻿#include "download.h"
#include <sstream>
#include <iomanip>

// 回调函数，用于写入下载的数据到文件函数的实现
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
    std::ofstream* ofs = static_cast<std::ofstream*>(userp);
    if (size * nmemb > 0) {
        ofs->write(static_cast<char*>(contents), size * nmemb);
    }
    return size * nmemb;
}

// 下载文件实现
int download_file(const std::string& url, const std::string& filename) {
    CURL* curl;
    CURLcode res;

    // 检查文件路径是否合法
    if (filename.empty() || !std::ofstream::binary || !std::ofstream().good()) {
        std::cerr << "文件名无效或打开失败：" << filename << std::endl;
        return 1;
    }

    // 初始化 curl
    curl = curl_easy_init();
    if (!curl) {
        std::cerr << "无法初始化 curl" << std::endl;
        return 1;
    }

    try {
        // 打开输出文件
        std::ofstream ofs(filename, std::ofstream::binary);
        if (!ofs) {
            std::cerr << "无法打开文件 " << filename << " 进行写入。" << std::endl;
            curl_easy_cleanup(curl);
            return 1;
        }

        // 配置 curl
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ofs);

        // 执行下载
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cerr << "下载失败: " << curl_easy_strerror(res) << std::endl;
            curl_easy_cleanup(curl);
            ofs.close();
            return 1;
        }

        // 清理资源
        curl_easy_cleanup(curl);
        ofs.close();

        std::cout << "文件已成功下载为 " << filename << std::endl;
        return 0;
    }
    catch (...) {
        std::cerr << "发生未知错误" << std::endl;
        if (curl) curl_easy_cleanup(curl);
        return 1;
    }
}
